import 'package:flutter/services.dart';

typedef HardwareScanCallback = void Function(String code);

class HardwareKeyboardListener {
  final HardwareScanCallback scanCallback;
  String code = '';
  String sendCode = '';

  HardwareKeyboardListener(this.scanCallback) {
    HardwareKeyboard.instance.addHandler(handler);
  }

  bool handler(KeyEvent event) {
    if (event is KeyDownEvent) {
      if (event.logicalKey.keyId == LogicalKeyboardKey.enter.keyId) {
        sendCode = code;
        code = '';
      }
      if (event.logicalKey.keyId != LogicalKeyboardKey.enter.keyId &&
          event.character != null) {
        code += event.character!;
      }
    } else if (event is KeyUpEvent) {
      if (event.logicalKey.keyId == LogicalKeyboardKey.enter.keyId) {
        scanCallback(sendCode);
      }
    }
    return true;
  }

  void dispose() {
    HardwareKeyboard.instance.removeHandler(handler);
  }
}
